<?php

/**
 * This is the model class for table "public.template".
 */
require_once(dirname(__FILE__).'/base/TemplateBase.php');
class Template extends TemplateBase
{
    const STATUS_DEACTIVE = 0, STATUS_ACTIVE = 1;
    
    /**
    * latest version of the template's html.
    * @var TemplateContent
    */
    public $Content;
    protected $masterLayout;
    public function relations()
    {
        return array(
            'contents'=>array(self::HAS_MANY, 'TemplateContent','template_id'),
            'currentRevision'=>array(self::HAS_ONE, 'TemplateContent','template_id', 'on'=>'"currentRevision".revision_id="t".revision_id')
        );
    }
    
    public function behaviors()
    {
        return array(
            'timestamp'=>array(
                'class'=>'TimestampBehavior',
            ),
        );
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('name', 'required'),
            array('name, group', 'length', 'max'=>100),
            array('masterLayout', 'numerical'),
            array('creation_datetime, last_update, status', 'safe'),
            array('id, name, group, status, creation_datetime, last_update', 'safe', 'on'=>'search'),
        );
    }
    
    public function getMasterLayout(){
        return $this->masterLayout;
    }
    
    public function getStatusOptions()
    {
        return array(
            self::STATUS_DEACTIVE => 'Deactive',
            self::STATUS_ACTIVE => 'Active',
        );
    }
    
    public function getStatusText()
    {
        $options = $this->getStatusOptions();
        return isset($options[$this->status]) ? $options[$this->status] : Yii::t('app', 'Unknown {att}', array('{att}'=>$this->status));
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => 'Name',
            'group' => 'Group',
            'status' => 'Status',
            'creation_datetime' => 'Creation Datetime',
            'last_update' => 'Last Update',
            'masterLayout'=>'Master layout'
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        $criteria=new CDbCriteria;

        $criteria->addSearchCondition('t.name',$this->name,true,'AND', 'LIKE');
        $criteria->addSearchCondition('t.group',$this->group,true,'AND', 'LIKE');
//        $criteria->addSearchCondition('t.group','master',true,'AND', 'NOT LIKE');
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'template_site ts ON ts.template_id = t.id';
        $criteria->compare('ts.site_id', Yii::app()->cmsManager->site['id']);

        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'name'
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
    
    protected function beforeSave() {
        // make the template alias
        if (empty($this->alias))
            $this->alias = toSlug($this->name);
        
        if ($this->masterLayout)
        {
            $this->group = 'master';
        }
        elseif ($this->group === 'master')
        {
            $this->group = '';
        }
        
        return parent::beforeSave();
    }
    
    protected function afterFind()
    {
        $this->masterLayout = false;
        if ($this->group === 'master')
        {
            $this->masterLayout = true;
        }
        return parent::afterFind();
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function unused()
    {
        //find templates used
        $criteria=new CDbCriteria;
        $criteria->select = 't.id';
        $criteria->join = 'INNER JOIN '.SITE_TABLE_PREFIX.'template_content tc ON tc.template_id = t.id';
        $criteria->join .= ' INNER JOIN '.SITE_TABLE_PREFIX.'page_revision pr ON pr.template_content_id = tc.id';
        /*$models = Template::model()->findAll($criteria);
        $usedTemplates = CHtml::listData($models, 'id', 'id');*/
        $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
        $usedSql = $command->getText();
        
        $criteria=new CDbCriteria;
        $criteria->addCondition(new CDbExpression('t.id NOT IN ('.$usedSql.')'));
        $criteria->addSearchCondition('t.name',$this->name,true,'AND', 'LIKE');
        $criteria->addSearchCondition('t.group',$this->group,true,'AND', 'LIKE');
//        $criteria->addSearchCondition('t.group','master',true,'AND', 'NOT LIKE');

        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'sort'=>array(
                'defaultOrder'=>'name'
            ),
            'pagination'=>array(
                'pageSize'=>Settings::BO_PAGE_SIZE,
            ),
        ));
    }
}
